package ems

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"time"
)

type JSONData struct {
	P   int      `json:"p"`
	Dev string   `json:"dev"`
	DT  string   `json:"dt"`
	ET  int      `json:"et"`
	PS  []PSItem `json:"ps"`
	DS  []int    `json:"ds"`
}

type PSItem struct {
	V float64 `json:"v"`
}

func GetDateTime() (t string) {
	now := time.Now()

	// 提取年月日时分秒
	year := now.Year() % 100
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()

	datetime := fmt.Sprintf("%02d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second)
	return (datetime)
}

func GetData() {
	logFile, err := os.OpenFile("c:/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("Failed to open log file: %v", err)
	}
	defer logFile.Close()

	// 设置日志输出目标为文件
	log.SetOutput(logFile)

	datetime := GetDateTime()
	//fmt.Println(datetime)
	data := JSONData{
		P:   3,
		Dev: "4c11ae60ad08",
		DT:  datetime,
		ET:  0,
		PS: []PSItem{
			{V: -99.9},
		},
		DS: []int{0, 1},
	}

	jsonBytes, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}

	encodedData := url.QueryEscape(string(jsonBytes))
	fmt.Println("Encoded JSON data:", encodedData)

	url := "http://192.168.1.211:8080/env/valueLogs/jucsan?pack=" + encodedData
	fmt.Println(url)

	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// 打印响应结果
	fmt.Println("Response:", string(body))
	log.Println(string(body))
}
